package com.caishi.lkx.exam.model;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zzw.common.entity.impl.BaseEntity;
import com.zzw.common.service.model.NameModel;
import com.zzw.common.service.model.base.BaseTreeModelV2;
import com.zzw.common.service.model.base.SortModel;
import com.caishi.lkx.exam.QuestionCollection;
import com.caishi.lkx.exam.QuestionCollectionBlockItem;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Schema(title = "章节")
@EqualsAndHashCode(callSuper = true)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "ex_chapters", autoResultMap = true)
public class ChapterModel extends BaseEntity<ChapterModel> implements
        NameModel<ChapterModel, String>,
        BaseTreeModelV2<ChapterModel, String>,
        SortModel<ChapterModel>,
        QuestionCollection<ChapterModel, String>,
        CstkModel,
        FreeModel<ChapterModel>{

    /**
     * 科目名称
     */
    private String name;

    /**
     * 后台显示名称
     */
    private String serverName;

    /**
     * 上级科目
     */
    private String parentId;

    private String path;

    @Schema(title = "叶子节点标志")
    private Boolean leaf;

    /**
     * 所属科目id
     */
    private Long categoryId;

    /**
     * 排序
     */
    private Integer sort;

    /**
     * 备注
     */
    private String remark;

    /**
     * 试题数
     */
    private Integer qcount;

    @JsonIgnore
    private String cstkId;

    @TableField(exist = false)
    private String categoryName;



    @TableField(value = "content", typeHandler = JacksonTypeHandler.class)
    @Schema(title = "章节内容")
    @JsonIgnore
    private List<Map<String, Object>> contentMap;

    @TableField(value = "question_ids", typeHandler = JacksonTypeHandler.class)
    private List<String> questionIds;

    @Schema(title = "免费标志")
    @TableField(exist = false)
    private Boolean free;

    @TableField(exist = false)
    private ChapterModel parent;

    @TableField(exist = false)
    private List<ChapterModel> children;
    public List<QuestionCollectionBlockItem> getContent() {
        if (contentMap != null) {
            return contentMap.stream().map(v -> BeanUtil.fillBeanWithMap(v, new QuestionCollectionBlockItem(), true)).toList();
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public void setContent(List<QuestionCollectionBlockItem> content) {
        if (content == null) {
            this.contentMap = null;
            return;
        }
        this.contentMap = content.stream().map(BeanUtil::beanToMap).toList();
    }

    @Override
    public String idCover(String id) {
        return id;
    }
}
